<?php namespace App\Console\Commands;

use HiCommon\Repository\OrderCheckpointRepository;
use HiCommon\Repository\OrderCheckpointVehicleRepository;
use HiCommon\Repository\ViewFinanceOrderRefundRepository;
use Illuminate\Console\Command;

error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);
class JPushNotice extends Command {

    protected $name = 'jpush_notice';//命令名称

    protected $description = '极光推送消息通知'; // 命令描述，没什么用

    /*
     * 步骤1 "* * * * * /root/queue_list.sh";//crontab -e 每分钟执行脚本文件queue_list.sh
     *
     *
     * 步骤2 脚本文件queue_list.sh
            "#!/bin/bash
            step=6
            for (( i = 0; i < 60; i = (i+step) )); do
                $(php /www/wwwroot/jctest.7deer.cn/artisan jpush_notice
            )
                sleep $step
            done

            exit 0";//脚本文件queue_list.sh内容
     * */

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
//        queue_in_notice_order_pay_success('WXFW2005190338214138','wxfw');

        //通知队列取出数据 默认10条
        $arr_data = predis_notice_queue_out();
        $n_count_data = count($arr_data);

        //有数据才去执行后续操作
        if($n_count_data > 0){
            foreach ($arr_data as $value)
            {
                //执行消息队列操作
                $result = $this->do_notice_queue($value);

                //如果执行操作失败，将数据重新塞入队列，等待再次执行
                if($result['state'] != 0){

                    $value['notice_fail_num'] = intval($value['notice_fail_num']) + 1;
                    $value['error_msg'] = $result['error'];
                    predis_notice_queue_in($value);
                }
            }

        }

        return 'ok';

    }

    /*执行消息队列操作*/
    public function do_notice_queue($arr_data){

        /*支付成功数据类型
        $arr_data = [
      'order_sn'=>$s_order_sn,//订单编号
      'notice_type'=>'njyy_pay_success',
        //支付成功类型
        njyy_pay_success    年检预约单支付成功
        ptshp_pay_success   普通商品单支付成功
        wxfw_pay_success    维修服务单支付成功
        wxby_pay_success    维修保养单支付成功
        dljy_pay_success    道路救援单支付成功
    ];
        */

        /*退款成功数据类型
    $arr_data = [
      'order_sn'=>$s_order_sn,//订单编号
      'refund_sn'=>$s_refund_sn,//售后编号
      'notice_type'=>'njyy_refund_success',
        //退款成功类型
        njyy_refund_success    年检预约单退款成功
        ptshp_refund_success   普通商品单退款成功
        wxfw_refund_success    维修服务单退款成功
        wxby_refund_success    维修保养单退款成功
        dljy_refund_success    道路救援单退款成功
    ];
*/
        try {
            //执行消息队列操作
            $s_notice_type = $arr_data['notice_type'];
            switch ($s_notice_type)
            {
                /********** 年检预约单 **********/
                //年检预约单-支付成功通知
                case 'njyy_pay_success':
                    $result = $this->notice_njyy_pay_success($arr_data);
                    break;

                //年检预约单-检测成功（合格）通知
                case 'njyy_check_ok':
                    $result = $this->notice_njyy_check($arr_data,'ok');
                    break;

                //年检预约单-检测成功（不合格）通知
                case 'njyy_check_not_ok':
                    $result = $this->notice_njyy_check($arr_data,'not_ok');
                    break;

                //年检预约单-检测失败（故障）通知
                case 'njyy_check_fail':
                    $result = $this->notice_njyy_check($arr_data,'fail');
                    break;

                //年检预约单-退款成功通知
                case 'njyy_refund_success':
                    $result = $this->notice_njyy_refund_success($arr_data);
                    break;

                /********** 普通商品订单 **********/
                //普通商品订单-支付成功
                case 'ptshp_pay_success':
                    $result = $this->notice_ptshp_pay_success($arr_data);
                    break;

                //普通商品订单-退款成功
                case 'ptshp_refund_success':
                    $result = $this->notice_ptshp_refund_success($arr_data);
                    break;

                //普通商品订单消息
                case 'ptshp_order_message_push':
                    $result = $this->ptshp_order_message_push_ing($arr_data);
                    break;

                //普通商品订单 售后 消息
                case 'ptshp_sales_message_push':
                    $result = $this->ptshp_sales_message_push_ing($arr_data);
                    break;

                /********** 维修服务订单 - 维修保养订单**********/
                //维修服务订单-支付成功
                case 'wxfw_pay_success':
                    $result = $this->notice_wxfw_wxby_pay_success($arr_data);
                    break;
                //维修保养订单-支付成功
                case 'wxby_pay_success':
                    $result = $this->notice_wxfw_wxby_pay_success($arr_data);
                    break;

                //维修服务单-退款成功
                case 'wxfw_refund_success':
                    $result = $this->notice_wxfw_wxby_refund_success($arr_data);
                    break;

                //维修保养单-退款成功
                case 'wxby_refund_success':
                    $result = $this->notice_wxfw_wxby_refund_success($arr_data);
                    break;

                //维修服务订单 - 维修保养订单 (所有消息)
                case 'wxby_order_message_push':
                    $result = $this->notice_wxby_message_push_ing($arr_data);
                    break;

                /********** 道路救援订单 **********/

                //道路救援-支付成功通知
                case 'dljy_pay_success':
//                    $result = $this->aa($arr_data);
                    $result = $this->notice_dljy_pay_success($arr_data);
                    break;
                //道路救援-退款成功通知
                case 'dljy_refund_success':
                    $result = $this->notice_dljy_refund_success($arr_data);
                    break;
                default:
                    $result =  hello_error('失败',[],'no order type!');
            }


            return $result;
        }
        catch (\Exception $exception) {
            return hello_error('失败-'.$exception->getMessage(),[],$exception->getMessage());
        }

    }

    /*年检预约单-支付成功通知*/
    public function notice_njyy_pay_success($arr_data = []){
        $s_order_sn = $arr_data['order_sn'];
        $arr_where = ['order_sn'=>$s_order_sn];
        $arr_option = [
          'with'=>['shop'],
          'field'=>['id','order_sn','main_type','user_id','shop_id'],
        ];
        $result = OrderCheckpointRepository::base_get_one($arr_where,$arr_option);
        if(is_null($result)){
            return hello_error('失败',[],'Order does not exist');
        }
        else{
            $arr_order = $result->toarray();

            //查询订单信息
            $img = $arr_order['shop']['logo']['full_src'];
            $title = '年检预约订单已支付成功！';
            $content = '您的年检预约订单已支付成功，订单编号：'.$arr_order['order_sn'];
            $user_id = $arr_order['user_id'];
            $pid = 3;
            $order_id = $arr_order['id'];
            $extras = [];
            $message_extras = [];
            $message_extras['order_type'] = 3;
            $message_extras['main_type'] = $arr_order['main_type'];
            add_message($img, $title,$content , $user_id,  $pid,$order_id,  $extras, $message_extras);
            return  hello_success('成功');
        }
    }

    /*年检预约单-车辆检测结果通知*/
    public function notice_njyy_check($arr_data = [],$check_type = ''){
        $n_order_vehicle_id = $arr_data['order_vehicle_id'];
        $arr_option = [
          'with'=>['order_simple.shop'],
          'field'=>['id','order_sn','order_checkpoint_id'],
        ];
        $result = OrderCheckpointVehicleRepository::base_find_one($n_order_vehicle_id,$arr_option);
        if(is_null($result)){
            return hello_error('失败',[],'Order does not exist');
        }
        else{
            $arr_order_vehicle = $result->toarray();
            $arr_order = $arr_order_vehicle['order_simple'];
            switch ($check_type)
            {
                case 'ok':
                    $msg_check_type = '检测成功【合格】';
                    break;
                case 'not_ok':
                    $msg_check_type = '检测成功【不合格】';
                    break;
                case 'fail':
                    $msg_check_type = '检测失败【故障】';
                    break;
                default:
                    $msg_check_type = '';

            }

            //查询订单信息
            $img = $arr_order['shop']['logo']['full_src'];
            $title = '年检预约订单车辆'.$msg_check_type.'！';
            $content = '您的'.$title.'，订单编号：'.$arr_order['order_sn'].'，车辆子单编号：'.$arr_order_vehicle['order_sn'];
            $user_id = $arr_order['user_id'];
            $pid = 3;
            $order_id = $arr_order['id'];
            $extras = [];
            $message_extras = [];
            $message_extras['order_type'] = 3;
            $message_extras['main_type'] = $arr_order['main_type'];

            add_message($img, $title,$content , $user_id,  $pid,$order_id,  $extras, $message_extras);
            return  hello_success('成功');
        }
    }

    /*年检预约单-车辆退款成功结果通知*/
    public function notice_njyy_refund_success($arr_data){
        $s_refund_sn = $arr_data['refund_sn'];
        $arr_where = ['order_sn'=>$s_refund_sn];
        $arr_option = [
          'with'=>['shop','njyy'],
          'field'=>['id','order_sn','out_trade_no','refund_fee','user_id','shop_id'],
        ];
        $result = ViewFinanceOrderRefundRepository::base_get_one($arr_where,$arr_option);
        if(is_null($result)){
            return hello_error('失败',[],'Order does not exist');
        }
        else{
            $arr_refund_order = $result->toarray();
            $arr_order = $arr_refund_order['njyy'];
            $arr_shop = $arr_refund_order['shop'];

            //查询订单信息
            $img = $arr_shop['logo']['full_src'];
            $title = '年检预约订单退款成功！';
            $content = '您的'.$title.'售后编号：'.$arr_refund_order['order_sn'];
            $user_id = $arr_refund_order['user_id'];
            $pid = 3;
            $order_id = $arr_order['id'];
            $extras = [];
            $message_extras = [];
            $message_extras['order_type'] = 3;
            $message_extras['main_type'] = $arr_order['main_type'];
            add_message($img, $title,$content , $user_id,  $pid,$order_id,  $extras, $message_extras);
            return  hello_success('成功');
        }
    }



    /*普通商品订单-支付成功*/
    public function notice_ptshp_pay_success($arr_data){
        //消息推送
        $arr_data['type'] = 36;
        $arr_data['order_no'] = $arr_data['order_sn'];
        $arr_data['title'] = '支付通知';
        $arr_data['content'] = '支付成功';
        return \Modules\Shop\Service\StoreOrderService::get_push_message($arr_data);
    }

    /*普通商品订单-退款*/
    public function notice_ptshp_refund_success($arr_data){
        //消息推送
        $arr_data['type'] = 32;
        $arr_data['refund_no'] = $arr_data['refund_sn'];
        $arr_data['title'] = '退款通知';
        $arr_data['content'] = '退款成功，请注意查收。';
        return \Modules\Shop\Service\StoreOrderRefundService::get_push_message($arr_data);
    }

    /*普通商品订单（消息推送）*/
    public function ptshp_order_message_push_ing($arr_data){
        return \Modules\Shop\Service\StoreOrderService::get_push_message($arr_data);
    }

    /*普通商品售后订单（所有消息推送）*/
    public function ptshp_sales_message_push_ing($arr_data){
        return \Modules\Shop\Service\StoreOrderRefundService::get_push_message($arr_data);
    }


    /*维修服务订单-维修保养订单-支付成功*/
    public function notice_wxfw_wxby_pay_success($arr_data){
        //消息推送
        $arr_data['type'] = 36;
        $arr_data['order_no'] = $arr_data['order_sn'];
        $arr_data['title'] = '支付通知';
        $arr_data['content'] = '支付成功';
        return \Modules\Shop\Service\OrderRepairService::notice_processing($arr_data);
    }

    /*维修服务订单-维修保养订单-退款*/
    public function notice_wxfw_wxby_refund_success($arr_data){
        //消息推送
        $arr_data['type'] = 32;
        $arr_data['order_no'] = $arr_data['order_sn'];
        $arr_data['title'] = '退款通知';
        $arr_data['content'] = '退款成功，请注意查收';
        return \Modules\Shop\Service\OrderRepairService::notice_processing($arr_data);
    }

    /*维修服务订单-维修保养订单（所有消息推送）*/
    public function notice_wxby_message_push_ing($arr_data){
        return \Modules\Shop\Service\OrderRepairService::notice_processing($arr_data);
    }

    /**  道路救援订单支付成功 **/
    public function notice_dljy_pay_success( $arr_data ){

        $arr_info = \HiCommon\Repository\RoadRescueOrderRepository::get_one_where( (array) ['order_sn'=>$arr_data['order_sn']] , (array) ['field'=>['id','pid','price','user_id','shop_id']]);
        $arr_list = road_rescue_server_type();
        $service_pid_image = '';
        $service_pid_name = '';
        foreach ( $arr_list as $key => $vo ){
            if( $vo['id'] == $arr_info['pid'] ){
                $service_pid_image = $vo['image'];
                $service_pid_name = $vo['name'];
            }
        }
        $temp['type'] = 36;   // 36：【订单消息】成功支付   详见add_message() 函数
        $temp['order_status'] = 1;              //当前的订单状态
        $temp['shop_id'] = $arr_info['shop_id'];        //店铺id
        $temp['order_type'] = 4;                        //订单类型   1：普通订单  2：服务订单  3：预约订单  4：道路救援订单  5：保养订单  6积分订单
        $temp['service_pid'] = $arr_info['pid'];            //服务类型

        $arr_jpush['extras']['pid'] = 3;                  //  極光推送扩展字段   1：系统消息   2：活动消息   3：订单消息
        add_message( $service_pid_image , '支付成功','您的道路救援订单【'.$service_pid_name.'】支付成功',$arr_info['user_id'],3,$arr_info['id'] , $arr_jpush , $temp );
        return hello_success('成功');
    }

    /** 道路救援退款成功推送 **/
    public function notice_dljy_refund_success( $arr_data ){
        $arr_option['field'] = ['id','price','pay_time','shop_id','user_id','pid'];
        $order = \HiCommon\Repository\RoadRescueOrderRepository::get_one_where( ['order_sn'=>$arr_data['order_sn']] ,$arr_option);
        $arr_list = road_rescue_server_type();
        $service_pid_image = '';
        $service_pid_name = '';
        foreach ( $arr_list as $key => $vo ){
            if( $vo['id'] == $order['pid'] ){
                $service_pid_image = $vo['image'];
                $service_pid_name = $vo['name'];
            }
        }
        //添加系统消息
        $temp['type'] = 32;  //【订单消息】退款成功
        $temp['price'] = $order['price'];
        $temp['order_status'] = 22;
        $temp['service_pid'] = $order['pid'];
        $temp['shop_id'] = $order['shop_id'];
        $temp['order_type'] = 4;

        $arr_jpush['extras']['pid'] = 3;
        $arr_jpush['extras']['service_pid'] = $order['pid'];
        $arr_jpush['extras']['order_id'] = $order['id'];
        add_message( $service_pid_image ,'已退款','您的道路救援订单【'.$service_pid_name.'】 已退款，请查收',$order['user_id'],3,$order['id'],$arr_jpush,$temp);


    }


}